package com.qifenqian.turbot.module.ui.restaurant

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.google.gson.Gson
import com.qifenqian.turbot.R
import com.qifenqian.turbot.area.GetJsonDataUtil
import com.qifenqian.turbot.area.JsonBean
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.module.contract.RestaurantContract
import com.qifenqian.turbot.module.presenter.RestaurantPresenter
import kotlinx.android.synthetic.main.activity_restaurant_address.*
import org.jetbrains.anko.indeterminateProgressDialog
import org.jetbrains.anko.toast
import org.json.JSONArray
import java.util.*

const val PARAM_PROVINCE = "province"
const val PARAM_CITY = "city"
const val PARAM_AREA = "area"
const val PARAM_ADDRESS = "address"

/**
 * @author H
 * @createDate 2019/1/7 11:44
 * @description 餐厅地址
 * @see
 * @since
 */

class RestaurantAddressActivity : BaseActivity<RestaurantPresenter, RestaurantContract.View>(), RestaurantContract.View {

    companion object {
        fun startThis(context: Context, province: String, city: String, area: String, address: String) {
            val intent = Intent(context, RestaurantAddressActivity::class.java)
            intent.putExtra(PARAM_PROVINCE, province)
            intent.putExtra(PARAM_CITY, city)
            intent.putExtra(PARAM_AREA, area)
            intent.putExtra(PARAM_ADDRESS, address)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.activity_restaurant_address
    }

    override fun bindPresenter(): RestaurantPresenter? {
        return RestaurantPresenter(this, this)
    }

    private var mProvince: String = ""
    private var mCity: String = ""
    private var mArea: String = ""
    private var mAddress: String = ""
    override fun initial() {
        mProvince = intent.getStringExtra(PARAM_PROVINCE)
        mCity = intent.getStringExtra(PARAM_CITY)
        mArea = intent.getStringExtra(PARAM_AREA)
        mAddress = intent.getStringExtra(PARAM_ADDRESS)
        tv_restaurant_address_address.text = mProvince + mCity + mArea
        et_restaurant_address_detail.setText(mAddress)
        progressDialog = indeterminateProgressDialog("加载中...")
        initAreaData()
        tv_restaurant_address_address.setOnClickListener {
            showPickerView()
        }
        btn_restaurant_address_next.setOnClickListener {
            if (tv_restaurant_address_address.text.toString() == "点击选择地址") {
                toast("请选择地址")
                return@setOnClickListener
            }
            if (et_restaurant_address_detail.text.toString().trim().isBlank()) {
                toast("请填写详细地址")
                return@setOnClickListener
            }
            mPresenter!!.changeAddress(mProvince, mCity, mArea, et_restaurant_address_detail.text.toString().trim())
        }
    }

    private var progressDialog: ProgressDialog? = null
    private fun showPickerView() {// 弹出选择器
        val pvOptions = OptionsPickerBuilder(this, OnOptionsSelectListener { options1, options2, options3, v ->
            //返回的分别是三个级别的选中位置
            mProvince = provinces[options1]
            mCity = cities[options1][options2]
            mArea = areas[options1][options2][options3]
            tv_restaurant_address_address.text = mProvince + mCity + mArea
        }).setTitleText("城市选择")
                .setSelectOptions(provinceMap[mProvince] ?: 0, cityMap[mCity] ?: 0, areaMap[mArea] ?: 0)
                .setDividerColor(resources.getColor(R.color.gray_999999))
                .setTextColorCenter(resources.getColor(R.color.gray_666666)) //设置选中项文字颜色
                .setContentTextSize(20)
                .build<String>()
        pvOptions.setPicker(provinces, cities, areas)   //三级选择器
        pvOptions.show()
    }

    private var provinces: MutableList<String> = mutableListOf()
    private val cities: MutableList<MutableList<String>> = mutableListOf()
    private val areas: MutableList<MutableList<MutableList<String>>> = mutableListOf()

    private var provinceMap: MutableMap<String, Int> = mutableMapOf()
    private var cityMap: MutableMap<String, Int> = mutableMapOf()
    private var areaMap: MutableMap<String, Int> = mutableMapOf()
    private var hasLoaded: Boolean = false

    private fun initAreaData() {//解析数据
        progressDialog!!.show()
        val jsonData = GetJsonDataUtil().getJson(this, "area.json")//获取assets目录下的json文件数据
        val jsonBean = parseData(jsonData)//用Gson 转成实体
        for (i in 0 until jsonBean.size) {
            provinces.add(jsonBean[i].pickerViewText)
            provinceMap[jsonBean[i].pickerViewText] = i
        }
        for (i in jsonBean.indices) {//遍历省份
            val cityList = mutableListOf<String>()//该省的城市列表（第二级）
            val provinceAreaList = mutableListOf<MutableList<String>>()//该省的所有地区列表（第三极）

            for (c in 0 until jsonBean[i].cityList.size) {//遍历该省份的所有城市
                val cityName = jsonBean[i].cityList[c].name
                cityList.add(cityName)//添加城市
                cityMap[cityName] = c
                val cityAreaList = ArrayList<String>()//该城市的所有地区列表
                if (jsonBean[i].cityList[c].area == null || jsonBean[i].cityList[c].area.size === 0) {
                    cityAreaList.add("")
                } else {
                    cityAreaList.addAll(jsonBean[i].cityList[c].area)
                }
                for (s in 0 until cityAreaList.size) {
                    areaMap[cityAreaList[s]] = s
                }
                provinceAreaList.add(cityAreaList)//添加该省所有地区数据
            }
            cities.add(cityList)
            areas.add(provinceAreaList)
            hasLoaded = true
            progressDialog!!.dismiss()
        }
    }

    private fun parseData(result: String): ArrayList<JsonBean> {//Gson 解析
        val detail = ArrayList<JsonBean>()
        try {
            val data = JSONArray(result)
            for (i in 0 until data.length()) {
                val entity = Gson().fromJson<JsonBean>(data.optJSONObject(i).toString(), JsonBean::class.java!!)
                detail.add(entity)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            hasLoaded = false
            progressDialog!!.dismiss()
            toast("加载失败")
            finish()
        }
        return detail
    }

    override fun changeAddressResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            finish()
        }
        toast(msg!!)
    }
}